import router, { routes } from './router'
import { useRouterStore } from '@/store/routerInfo/index.ts'

const store = useRouterStore()

const whiteList = ['/login', '/dyDashboard'] // 不重定向白名单

router.beforeEach(async (to, from, next) => {
  const token = sessionStorage.getItem('token')
  console.log(123456, token)
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      console.log(111, store.isAddRoute)
      if (store.isAddRoute) {
        next()
        return
      }
      const routerInfo = await store.getRouters() || []
      console.log(33333, routerInfo)
      store.addRouterInfo(routerInfo)
      routerInfo.forEach(i => {
        router.addRoute(i)
      })
      const redirectPath = from.query.redirect || to.path
      const redirect = decodeURIComponent(redirectPath)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      store.setAddRoute(true)
      next(nextData)
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

// router.afterEach((to) => {
//   useTitle(to?.meta?.title as string)
//   done() // 结束Progress
//   loadDone()
// })
